<template>
  <basic-container>
    <el-steps :active="active" align-center>
      <el-step title="设备注册" />
      <el-step title="设备接入" />
      <el-step title="连接验证" />
      <el-step title="设备量产" />
    </el-steps>
    <div v-show="active===1" class="step-div">
      <el-row>
        <el-text>在您进行设备开发之前，需要先注册设备。</el-text>
      </el-row>
      <el-row>
        <el-text size="small">
          请注意：每个设备都隶属于某个特定产品。物联网平台将为每个设备颁发唯一的证书，即设备名称（DeviceName）和设备密钥（DeviceSecret），设备需要使用这两个证书与平台进行通信。
        </el-text>
      </el-row>
      <el-row>
        <el-card class="cursor card-container" shadow="hover" @click="viewDeviceList">
          <div class="content-container">
            <div class="image-container">
              <img src="/svg/icon1.svg">
            </div>
            <div class="text-container">
              <p>前往添加设备</p>
            </div>
          </div>
        </el-card>
      </el-row>
      <el-row>
        <el-text size="small">如果您已添加过设备，可直接进入下一步。</el-text>
      </el-row>
    </div>
    <div v-show="active===2" class="step-div">
      <div>
        <el-divider />
        <el-row>
          <el-text>设备开发与配置信息</el-text>
        </el-row>
        <el-row>
          <el-text size="small">1. 使用开发配置信息来进行设备证书烧写与配置</el-text>
        </el-row>
        <el-row>
          <el-text>设备信息：</el-text>
          <avue-input-table :props="deviceProps"
                            :children="deviceChildren"
                            :formatter="deviceFormatter"
                            :on-load="onLoadDevice"
                            v-model="deviceId"
                            placeholder="请选择设备" style="width: 350px">
          </avue-input-table>
        </el-row>
        <el-row>
          <highlight v-if="deviceId > 0" :code="deviceCode" language="json" />
        </el-row>
        <el-row v-if="deviceId > 0">
          <el-text>连接信息：</el-text>
          <el-select v-model="domainId" placeholder="请选择接入方式" @change="domainChange" style="width: 350px">
            <el-option
              v-for="item in domainSelect"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-row>
        <el-row v-if="deviceId > 0">
          <el-alert type="info" show-icon :closable="false">
            <template #title>
              <el-text size="small">注意：这里仅仅为 临时调试 所用，密钥有效期为 5
                分钟，真实设备连接参数请按加密文档生成。
              </el-text>
            </template>
          </el-alert>
        </el-row>
        <el-row>
          <highlight v-if="domainId > 0" :code="domainCode" language="json" />
        </el-row>
      </div>
    </div>
    <!--    <div v-show="active===2" class="step-div">
          <el-row>
            <el-text>设备开发语言/版本</el-text>
          </el-row>
          <el-row>
            <el-text size="small">请选择您的设备开发语言/版本：</el-text>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="4" v-for="(item, index) in items" :key="index">
              <el-card
                  :class="{ 'card-selected': selectedIndex === index , cursor: true }"
                  shadow="hover"
                  @click="selectCard(index)"
              >
                {{ item }}
              </el-card>
            </el-col>
          </el-row>
          <div v-if="this.selectedIndex >= 0">
            <el-divider/>
            <el-row>
              <el-text>设备开发与配置信息</el-text>
            </el-row>
            <el-row>
              <el-text size="small">1. 前往下载对应开发语言 SDK，并按照开发文档指引来操作下载本Demo将默认您同意软件使用协议
              </el-text>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="6">
                <el-card class="cursor card-container" shadow="hover" @click="downloadDoc">
                  <div class="content-container">
                    <div class="image-container">
                      <img src="/svg/icon2.svg">
                    </div>
                    <div class="text-container">
                      <p>下载 {{ this.items[this.selectedIndex] }} 开发文档</p>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="cursor card-container" shadow="hover" @click="downloadCode">
                  <div class="content-container">
                    <div class="image-container">
                      <img src="/svg/icon3.svg">
                    </div>
                    <div class="text-container">
                      <p>下载 {{ this.items[this.selectedIndex] }} 代码包</p>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <el-row>
              <el-text size="small">2. 使用开发配置信息来进行设备证书烧写与配置</el-text>
            </el-row>
            <el-row>
              <el-text>设备信息：</el-text>
              <avue-input-table :props="deviceProps"
                                :children="deviceChildren"
                                :formatter="deviceFormatter"
                                :on-load="onLoadDevice"
                                v-model="deviceId"
                                placeholder="请选择设备" style="width: 350px"></avue-input-table>
            </el-row>
            <el-row>
              <highlight v-if="deviceId > 0" :code="deviceCode" language="json"/>
            </el-row>
            <el-row v-if="deviceId > 0">
              <el-text>连接信息：</el-text>
              <el-select v-model="domainId" placeholder="请选择接入方式" @change="domainChange" style="width: 350px">
                <el-option
                    v-for="item in domainSelect"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-row>
            <el-row v-if="deviceId > 0">
              <el-alert type="info" show-icon :closable="false">
                <template #title>
                  <el-text size="small">注意：这里仅仅为 临时调试 所用，密钥有效期为 5 分钟，真实设备连接参数请按加密文档生成。</el-text>
                </template>
              </el-alert>
            </el-row>
            <el-row>
              <highlight v-if="domainId > 0" :code="domainCode" language="json"/>
            </el-row>
          </div>
        </div>-->
    <div v-show="active===3" class="step-div">
      <el-row>
        <el-text>烧录完成后，您可通过下方来验证设备联网状态</el-text>
      </el-row>
      <el-row>
        <el-card shadow="hover" class="box-card">
          <template #header>
            <div class="card-header">
              <el-text>设备详细信息，点击查看 =></el-text>
              <el-link type="primary" @click="viewDevice">设备详情</el-link>
            </div>
          </template>
          <el-row>
            <el-text>ProductKey：</el-text>
            <el-text>{{ this.productKey }}</el-text>
          </el-row>
          <el-row>
            <el-text>DeviceName：</el-text>
            <el-text>{{ this.deviceData.deviceName }}</el-text>
          </el-row>
          <el-row>
            <el-text>设备状态：</el-text>
            <el-text v-if="this.deviceData.deviceStatus===1" type="success">
              <el-icon>
                <SuccessFilled />
              </el-icon>
              {{ this.deviceData.deviceStatusName }}
            </el-text>
            <el-text v-else-if="this.deviceData.deviceStatus===2" type="danger">
              <el-icon>
                <WarningFilled />
              </el-icon>
              {{ this.deviceData.deviceStatusName }}
            </el-text>
            <el-text v-else type="info">
              <el-icon>
                <CircleCloseFilled />
              </el-icon>
              {{ this.deviceData.deviceStatusName }}
            </el-text>
            <el-divider direction="vertical" />
            <el-text type="primary" size="small" class="cursor" @click="this.initDevice(this.deviceData.id)">刷新
            </el-text>
          </el-row>
          <el-row>
            <el-text>设备日志：</el-text>
            <el-text type="primary" size="small" class="cursor" @click="viewDeviceLog">查看日志</el-text>
          </el-row>
        </el-card>
      </el-row>
      <el-row>
        <el-text>
          当设备状态显示为在线时，表示您的设备已成功连接。后续您可以利用物联网平台的消息通信功能，进行设备消息的收发与调试。
        </el-text>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-card class="cursor card-container" shadow="hover" @click="routerServerRelay">
            <div class="content-container">
              <div class="image-container">
                <img src="/svg/icon4.svg">
              </div>
              <div class="text-container">
                <p>服务端订阅</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="cursor card-container" shadow="hover" @click="routerSimulator">
            <div class="content-container">
              <div class="image-container">
                <img src="/svg/icon1.svg">
              </div>
              <div class="text-container">
                <p>设备模拟器</p>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="cursor card-container" shadow="hover" @click="routerDebugger">
            <div class="content-container">
              <div class="image-container">
                <img src="/svg/icon3.svg">
              </div>
              <div class="text-container">
                <p>设备调试器</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div v-show="active===4" class="step-div">
      <el-row>
        <el-text>批量添加设备</el-text>
      </el-row>
      <el-row>
        <el-card class="cursor card-container" shadow="hover" @click="handleDeviceBatch">
          <div class="content-container">
            <div class="image-container">
              <img src="/svg/icon7.svg">
            </div>
            <div class="text-container">
              <p>批量添加</p>
            </div>
          </div>
        </el-card>
        <el-dialog v-model="deviceVisible" title="批量添加设备" width="500">
          <avue-form ref="form" v-model="deviceForm" :option="deviceOption" @submit="handleSubmit"></avue-form>
        </el-dialog>
      </el-row>
      <el-row>
        <el-text>证书量产烧写方案</el-text>
      </el-row>
      <el-row>
        <el-text size="small">1. 产线烧写方案</el-text>
      </el-row>
      <el-row>
        <el-text size="small">
          设备厂商在产线上将预先申请到的设备证书烧录到设备中。设备通电后，会自动连接到物联网平台进行认证。
        </el-text>
      </el-row>
      <el-row>
        <el-text size="small">2. 云端下发方案</el-text>
      </el-row>
      <el-row>
        <el-text size="small">
          设备通电后，首先连接到厂商的云端服务，向云端申请设备证书。云端服务将证书发送给设备，设备再使用该证书连接物联网平台进行认证。厂商需自行实现该证书申请机制，物联网平台提供
          <el-text type="primary" size="small">注册设备 API</el-text>
          供厂商调用。
        </el-text>
      </el-row>
    </div>
    <div class="step-center">
      <el-button style="margin-top: 12px" v-if="this.active > 1" @click="previous">上一步</el-button>
      <el-button style="margin-top: 12px" v-if="this.active < 4" @click="next">下一步</el-button>
    </div>
  </basic-container>
</template>

<script>
import { getList as getDeviceList, getDetail as getDeviceDetail, batchSubmit } from '@/api/iot/device';
import { getDetailByKey as getProductDetail } from '@/api/iot/product';
import func from '@/utils/func';
import { getDeviceMqttLinks } from '@/api/iot/mqtt/links';
import { validatenull } from '@/utils/validate';

export default {
  name: 'productDevice',
  props: {
    productKey: String,
    productId: String
  },
  data() {
    return {
      // 用于保存当前步骤
      active: 1,
      // 用于保存当前选中的el-card的索引
      selectedIndex: -1,
      // 模拟的el-card显示内容
      items: ['C', 'C(Extend)', 'Android', 'Java', 'Python', 'Node.js', 'IOS'],
      // 设备数据
      deviceVisible: false,
      deviceForm: {},
      deviceOption: {
        column: [
          {
            label: '产品名称',
            prop: 'productName',
            disabled: true,
            span: 24
          },
          {
            label: 'productKey',
            prop: 'productKey',
            disabled: true,
            span: 24
          },
          {
            label: '添加方式',
            prop: 'batchTool',
            type: 'radio',
            dicData: [
              {
                label: '自动生成',
                value: 1
              }
            ],
            value: 1,
            span: 24
          },
          {
            label: '数量',
            labelTip: '单次最多添加 500 台，系统会自动生成全局唯一的 DeviceName 和 DeviceSecret',
            prop: 'batchSize',
            type: 'number',
            max: 500,
            span: 24
          }
        ]
      },
      productData: {},
      deviceId: '',
      deviceName: '',
      deviceData: {},
      deviceCode: '',
      deviceProps: {
        label: 'deviceName',
        value: 'id'
      },
      deviceChildren: {
        border: true,
        column: [{
          label: '产品编号',
          prop: 'productKey',
          width: 200
        }, {
          label: '设备名称',
          prop: 'deviceName',
          search: true,
          width: 250
        }, {
          label: '设备密钥',
          prop: 'deviceSecret',
          search: true
        }, {
          label: '唯一编号',
          prop: 'uniqueNo',
          search: true
        }, {
          label: '设备状态',
          prop: 'deviceStatusName',
          width: 120
        }, {
          label: '激活时间',
          prop: 'activeTime',
          width: 180
        }]
      },
      // 域名数据
      domainId: '',
      domainCode: '',
      domainSelect: [
        {
          label: 'MQTT',
          value: 1
        }
      ]
    };
  },
  watch: {
    deviceId() {
      if (!validatenull(this.deviceId)) {
        this.initDevice(this.deviceId);
        this.domainChange(1);
      }
    }
  },
  computed: {},
  created() {
    this.initProduct();
  },
  methods: {
    initProduct() {
      getProductDetail(this.productKey).then(res => {
        this.productData = res.data.data;
        this.deviceForm.productName = this.productData.productName;
        this.deviceForm.productKey = this.productData.productKey;
      });
    },
    initDevice(deviceId) {
      getDeviceDetail(deviceId).then(res => {
        this.deviceData = res.data.data;
        this.deviceName = this.deviceData.deviceName;
        this.deviceCode = `{"productKey":"${this.productKey}","deviceName": "${this.deviceData.deviceName}","deviceSecret": "${this.deviceData.deviceSecret}"}`;
      });
    },
    deviceFormatter(row) {
      if (!row.deviceName) return '';
      return row.deviceName + '｜' + row.deviceSecret;
    },
    onLoadDevice({ page, value, data }, callback) {
      let param = {};
      let currentPage = 1;
      let pageSize = 10;
      //首次查询信息
      if (value) {
        getDeviceDetail(value).then(res => {
          callback(res.data.data);
        });
        return;
      }
      if (data) {
        param = data;
      }
      if (page) {
        currentPage = page.currentPage;
        pageSize = page.pageSize;
      }
      //分页查询信息
      getDeviceList(currentPage, pageSize, Object.assign(param, { productKey: this.productKey })).then(res => {
        const data = res.data.data;
        callback({
          total: data.total,
          data: data.records
        });
      });
    },
    previous() {
      if (this.active-- === 1) {
        this.active = 1;
      }
    },
    next() {
      if (this.active === 2) {
        if (func.toInt(this.deviceId) < 0 || func.toInt(this.domainId) < 0) {
          this.$message.warning('请依次选择开发语言/设备/接入方式');
          return false;
        }
      }
      if (this.active++ > 3) {
        this.active = 1;
      }
    },
    // 更新选中状态的方法
    selectCard(index) {
      this.selectedIndex = index;
    },
    viewDevice() {
      window.open(`/iot/device/detail/${this.productKey}/${this.deviceName}`);
    },
    viewDeviceLog() {
      window.open(`/iot/device/detail/${this.productKey}/${this.deviceName}?activeKey=log`);
    },
    viewDeviceList() {
      window.open(`/iot/device?productKey=${this.productKey}&productId=${this.productId}`);
    },
    downloadCode() {
      this.$message({
        message: `下载${this.items[this.selectedIndex]}代码包`,
        type: 'success'
      });
    },
    downloadDoc() {
      this.$message({
        message: `下载${this.items[this.selectedIndex]}开发文档`,
        type: 'success'
      });
    },
    routerServerRelay() {
      window.open(`/iot/server/relay?productKey=${this.productKey}`);
    },
    routerSimulator() {
      window.open('/iot/deviceSimulator');
    },
    routerDebugger() {
      window.open('/iot/deviceDebugger');
    },
    handleDeviceBatch() {
      this.deviceVisible = true;
    },
    domainChange(value) {
      this.domainId = value;
      getDeviceMqttLinks(this.deviceId).then(res => {
        this.domainCode = JSON.stringify(res.data.data);
      });
    },
    handleSubmit(form, done, loading) {
      batchSubmit(this.productKey, form.batchSize).then(() => {
        this.$message({
          type: 'success',
          message: '设备批量添加成功!'
        });
        this.$refs.form.resetForm();
        this.deviceVisible = false;
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    }
  }
};
</script>

<style>
.cursor {
  cursor: pointer;
}

.step-center {
  text-align: center;
}

.step-div {
  margin-top: 30px;
}

.card-container {
  width: 300px;
  height: 100px;
  display: flex;
  align-items: center;
}

.content-container {
  display: flex;
  align-items: center;
  width: 350px;
  height: 100px;
}

.image-container {
  flex: 1;
  display: flex;
  align-items: center;
}

.image-container img {
  width: 80px;
  height: 80px;
}

.text-container {
  flex: 3;
  display: flex;
  align-items: center;
  text-align: left;
}

/* 添加的选中效果样式 */
.card-selected {
  border: 2px solid #409eff; /* Element Plus主题色 */
  transform: scale(1.05); /* 轻微放大效果 */
  transition: all 0.3s; /* 平滑过渡效果 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  width: 480px;
}

</style>
